
package jwww.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

import org.apache.log4j.Logger;

public class QuickProcess
  extends Thread
{
  List<String>   command   = null;
  String output    = null;
  int    exitValue = -1;

  Map<String,String> env = new HashMap<String,String>();

  Logger logger = null;

  /** Starts the process and returns on completion.
      Use output() to retrieve the output.
  */
  public QuickProcess(String command)
  {
    this(TextReader.list(command));
  }

  public QuickProcess(String[] command)
  {
    this(StringUtil.stringList(command));
  }

  /** Starts the process and returns on completion.
      Use output() to retrieve the output.
  */
  public QuickProcess(List<String> command)
  {
    this.command = command;
    logger = Logger.getLogger("JWWW");
  }

  public void setenv(String[] args)
  {
    for (String arg : args)
    {
      String[] kv = arg.split("=");
      if (kv.length < 2)
      {
        logger.warn("QuickProcess.setenv(): bad key/value: " + arg);
        continue;
      }
      env.put(kv[0],kv[1]);
    }
  }

  /** Should not be called externally.
   */
  @Override
  public void run()
  {
    output    = null;
    exitValue = -1;
    try
    {
      ProcessBuilder pb = new ProcessBuilder(command);
      pb.redirectErrorStream(true);
      pb.environment().putAll(env);
      Process        process = pb.start();
      StringBuilder  builder = new StringBuilder(4096);
      BufferedReader in =
        new BufferedReader
        (new InputStreamReader(process.getInputStream()));

      int    n     = 0;
      int    chunk = 4096;
      char[] buf   = new char[chunk];
      while (true)
      {
        n = in.read(buf, 0, chunk);
        if (n < 0)
          break;
        builder.append(buf, 0, n);
      }

      process.waitFor();
      output    = builder.toString();
      exitValue = process.exitValue();
    }
    catch (Exception e)
    {
      System.out.println(e);
    }
  }

  public String output()
  {
    return output;
  }

  public int exitValue()
  {
    return exitValue;
  }

  public static void main(String[] args)
  {
    List<String> list = new ArrayList<String>();
    list.add("head");
    list.add("build.xml");
    // QuickProcess qp = new QuickProcess(list);
    QuickProcess qp = new QuickProcess("head build.xml");
    System.out.println(qp.output());
    System.out.println("exit: " + qp.exitValue());
  }
}
